package uk.ac.imperial.gpaexpress.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class SharePanel extends Composite {
	UserInterface ui;
	
	private static final Binder binder = GWT.create(Binder.class);

	interface Binder extends UiBinder<Widget, SharePanel> {
	}
	
	@UiField VerticalPanel sharePanel;
	@UiField Button cancelButton;
	@UiField Button confirmButton;
	@UiField TextBox shareText;
	@UiField TextArea messageText;
	
	public SharePanel(UserInterface ui) {
		initWidget(binder.createAndBindUi(this));
		this.ui = ui;
	}
	
	@UiHandler("cancelButton")
	void cancelClick(ClickEvent event){
		DialogBox parent = (DialogBox) sharePanel.getParent().getParent().getParent();
		parent.hide();
	}
	
	@UiHandler("confirmButton")
	void confirmClick(ClickEvent event){
		try {
			String model = ui.modelList.getValue(ui.modelList.getSelectedIndex());
			String shareWith = shareText.getText();
			String message = messageText.getText();
			RequestBuilder shareRequest = new RequestBuilder(RequestBuilder.POST, "/Query");
			shareRequest.setHeader("type", "share");
			shareRequest.setHeader("model", model);
			shareRequest.setHeader("shareWith", shareWith);
			shareRequest.setHeader("message", message);
			shareRequest.sendRequest(null, new RequestCallback(){
				public void onResponseReceived(Request request, Response response) {
					ui.tickerIdle();
				}
				public void onError(Request request, Throwable exception) {
					
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		DialogBox parent = (DialogBox) sharePanel.getParent().getParent().getParent();
		parent.hide();
	}

}
